package com.develope.plant.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.provider.Settings;
import android.text.TextUtils;

import com.develope.plant.BaseApplication;
import com.develope.plant.R;

public class Utils {
	
	public static boolean isEnableNetwork() {
	    Context context = BaseApplication.getContext();
	    if(context == null) return true;
        ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected();
    }
	
	public static boolean isEnableNetwork(Activity controller, boolean isAlert) {
		boolean result = isEnableNetwork();
		if(!result && controller != null) {
			Alerts.showButtonDialog(controller, controller.getString(R.string.cm_error), 
					controller.getString(R.string.NETWORK_ERROR_MESSAGE), null);

		}
		return result;
	}
	
	public static boolean isLocationServiceEnabled(final Activity context, boolean isShowDialog) {
		LocationManager lm = (LocationManager) BaseApplication
				.getContext().getSystemService(Context.LOCATION_SERVICE);
		boolean gps_enabled = false;
		boolean network_enabled = false;
		try {
			gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		} catch (Exception ex) {
			Logger.error("LocationManager.GPS_PROVIDER exception:" + ex.getMessage());
		}
		try {
			network_enabled = lm
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		} catch (Exception ex) {
			Logger.debug("LocationManager.NETWORK_PROVIDER exception:" + ex.getMessage());
		}
		if (!gps_enabled && !network_enabled) {
		    if(context != null && isShowDialog){
		    	Alerts.show2ButtonDialog(context, null, "Do you want to enable Location Service?", new OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
		    			context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
					};
				});
		    }
			return false;
		}
		return true;
	}
	
	public static final String DDMMYYYY = "dd/MM/yyyy";
	public static String dateToStringDDMMYYYY(Date datetime){
		return dateToString(datetime, DDMMYYYY);
	}
	
	public static String dateToString(Date datetime, String format){
		if(datetime == null) {
			datetime = Calendar.getInstance().getTime();
		}
		if(TextUtils.isEmpty(format)) {
			format = DDMMYYYY;
		}
		
		SimpleDateFormat dft = new SimpleDateFormat(format, Locale.getDefault());
		return dft.format(datetime);
	}
}
